import React from "react";
import {useLocation, matchPath} from "react-router-dom";
import {Breadcrumb} from "antd";
import {findSideBarRoutes} from "@/routes";
import {XRoutes} from "@/routes/types";

import './index.less';

// 根据 pathname 找到对应的 title
const findBreadcrumbTitle = (pathname: string, routes: XRoutes): any => {
    for (let i = 0; i < routes.length; i++) {
        const route = routes[i];
        
        if (route.path === pathname) {
            return [{title: route.meta?.title as string}];
        }
        
        if (route.children) {
            for (let j = 0; j < route.children.length; j++) {
                const childRoute = route.children[j];
                // 为了路由的 params 参数能匹配上，必须使用 matchPath 方法
                if (matchPath(childRoute.path as string, pathname)) {
                    return [
                        {title: route.meta?.title as string},
                        {title: childRoute.meta?.title}
                    ];
                }
            }
        }
    }
    return [];
};

function BreadCrumb() {
    const location = useLocation();
    const {pathname} = location;
    // 获取需要遍历的路由表
    const routes = findSideBarRoutes();
    // 生成导航
    const items = findBreadcrumbTitle(pathname, routes);
    
    return (
        <Breadcrumb style={{margin: "15px 10px"}} items={items}/>
    );
}

export default BreadCrumb;
